/**
 * [
 *   ['2012-03', '2014-06'],
 *   ['2012-06', '2018-09'],
 *   ['2022-01', 'present']
 * ]
 *
 * 计算工作经历时间, 时间阶段可能存在交叉
 */

function solution(ranges) {
  const length = ranges.length;
  if (length < 1) return 0;
  const line = [];
  for (const range of ranges) {
    const [start, end] = range.map(toNum);
    line.push({
      value: start,
      mark: "start",
    });
    line.push({
      value: end,
      mark: "end",
    });
  }

  line.sort((a, b) => a.value - b.value);

  let acc = 0;
  let startMarkCount = 0;
  let preStart;

  for (const { value, mark } of line) {
    if (startMarkCount === 0) {
      // 一定是start
      preStart = value;
    }

    if (mark === "start") {
      startMarkCount++;
    } else {
      startMarkCount--;
    }

    if (startMarkCount === 0) {
      // 一定是end
      acc += value - preStart;
    }
  }

  return acc / 1000 / 60 / 60 / 24; // 天数
}

function toNum(date = "2000-01") {
  const base = new Date("2000-01").getTime();
  if (date === "present") {
    date = new Date();
    date = `${date.getFullYear()}-${("0" + (date.getMonth() + 1)).slice(-2)}`;
  }
  return new Date(date).getTime() - base;
}

solution([
  ["2012-03", "2014-06"],
  ["2012-06", "2018-09"],
  ["2022-01", "present"],
]);
